package controllers

import (
	"fmt"
	"gitee.com/falling-ts/gower/app"
	"gitee.com/falling-ts/gower/app/admin/requests"
	"gitee.com/falling-ts/gower/app/models"
	"gitee.com/falling-ts/gower/services"
	"math"
)

type RoleController struct {
	app.Controller
	resource    string
	breadcrumbs []map[string]any
}

var Role = &RoleController{
	Controller: app.Controller{},
	resource:   "/admin/system/role",
	breadcrumbs: []map[string]any{
		{
			"name": "系统设置",
			"path": "#",
		},
		{
			"name": "角色管理",
			"path": "/admin/system/role",
		},
	},
}

// Index 获取列表页面
func (r *RoleController) Index(req *requests.RoleIndexRequest) (services.Response, error) {
	var (
		roleModels []models.AdminRole
		total      int64
	)

	query := db.GormDB()
	if req.Name != "" {
		query = query.Where("name LIKE ?", "%"+req.Name+"%")
	}
	if req.Flag != "" {
		query = query.Where("flag LIKE ?", "%"+req.Flag+"%")
	}

	query.Model(&roleModels).Count(&total)
	query.Order("id desc").
		Limit(req.PageNum).
		Offset((req.Page - 1) * req.PageNum).
		Find(&roleModels)

	lastPage := int(math.Ceil(float64(total) / float64(req.PageNum)))
	paging := make([]int, lastPage)
	for i := range paging {
		paging[i] = i + 1
	}

	data, err := app.Trans(roleModels, app.Rule{
		"id":   "||",
		"name": "||",
		"flag": "||",
	})
	if err != nil {
		return nil, exc.BadRequest(err)
	}

	return res.Ok("admin/system/role/index", app.Data{
		"breadcrumbs": r.breadcrumbs,
		"resource":    r.resource,
		"filters": []map[string]any{
			{
				"label": "角色名称",
				"name":  "name",
				"value": req.Name,
				"type":  "text",
			},
			{
				"label": "角色标记",
				"name":  "flag",
				"value": req.Flag,
				"type":  "text",
			},
		},
		"pinRow":       true,
		"pinCol":       false,
		"showSelector": false,
		"showCreate":   true,
		"showEdit":     true,
		"showView":     true,
		"showDel":      true,
		"useModal":     true,
		"cols": []map[string]any{
			{
				"label": "角色名称",
				"field": "name",
				"type":  "text",
			},
			{
				"label": "角色标记",
				"field": "flag",
				"type":  "text",
			},
		},
		"data":        data,
		"total":       total,
		"paging":      paging,
		"currentPage": req.Page,
		"lastPage":    lastPage,
	}), nil
}

// Create 获取添加页面
func (r *RoleController) Create(req *requests.RoleCreateEditRequest) (services.Response, error) {
	return res.Ok("admin/system/role/form", app.Data{
		"isModal": req.IsModal,
		"breadcrumbs": append(r.breadcrumbs, map[string]any{
			"name": "新增",
			"path": "/admin/system/role/create",
		}),
		"resource": r.resource,
		"forms": []map[string]any{
			{
				"label":    "角色名称",
				"name":     "name",
				"type":     "text",
				"required": true,
			},
			{
				"label":    "角色标记",
				"name":     "flag",
				"type":     "text",
				"required": true,
			},
		},
		"useApi":     true,
		"storeApi":   "roleStore",
		"updateApi":  "roleUpdate",
		"destroyApi": "roleDestroy",
	}), nil
}

// Store 添加数据
func (r *RoleController) Store(req *requests.RoleStoreRequest, role *models.AdminRole) (services.Response, error) {
	_, err := role.In(req, app.Rule{
		"_skips": app.Skips{},
	})
	if err != nil {
		return nil, exc.BadRequest(err)
	}
	result := db.Create(role)
	if result.Error != nil {
		return nil, exc.BadRequest(trans.DBError(result.Error))
	}

	return res.SeeOther(r.resource, "创建成功"), nil
}

// Edit 获取修改页面
func (r *RoleController) Edit(req *requests.AdminCreateEditRequest, role *models.AdminRole) (services.Response, error) {
	return res.Ok("admin/system/role/form", app.Data{
		"isModal": req.IsModal,
		"breadcrumbs": append(r.breadcrumbs, map[string]any{
			"name": "修改",
			"path": fmt.Sprintf("/admin/system/admin/%s/edit", role.IDString()),
		}),
		"resource": r.resource,
		"id":       role.ID,
		"forms": []map[string]any{
			{
				"label": "角色名称",
				"name":  "name",
				"type":  "text",
				"value": role.Name,
			},
			{
				"label": "角色标记",
				"name":  "flag",
				"type":  "text",
				"value": role.Flag,
			},
		},
		"useApi":     true,
		"storeApi":   "roleStore",
		"updateApi":  "roleUpdate",
		"destroyApi": "roleDestroy",
	}), nil
}

// Update 修改数据
func (r *RoleController) Update(req *requests.RoleUpdateRequest, role *models.AdminRole) (services.Response, error) {
	_, err := role.In(req, app.Rule{
		"_skips": app.Skips{},
	})
	if err != nil {
		return nil, exc.BadRequest(err)
	}

	result := db.Save(role)
	if result.Error != nil {
		return nil, exc.BadRequest(trans.DBError(result.Error))
	}

	return res.SeeOther(r.resource, "修改成功"), nil
}

// Show 获取详情
func (*RoleController) Show(req *requests.RoleRequest, model *models.AdminRole) (services.Response, error) {
	return res.Ok("admin/system/role/index", app.Data{
		"model": model,
	}), nil
}

// Destroy 销毁数据
func (*RoleController) Destroy(model *models.AdminRole) (services.Response, error) {
	result := db.Delete(model)
	if result.Error != nil {
		return nil, exc.BadRequest(result.Error)
	}

	return res.NoContent("删除成功"), nil
}
